<?php
namespace app\controller;

use think\facade\Cookie;
use think\facade\Db;
use think\facade\View;

class Login
{
    public function index(){
        return View::fetch();
    }

    //登录接口
    public function login(){
        $username = trim(input('post.username'));
        $password = trim(input('post.password'));
        $code = trim(input('post.code'));
        $remember = input('post.remember');

        if(empty($username)){
            return_json(1,'请输入用户名');
        }

        if(empty($password)){
            return_json(1,'请输入密码');
        }

        if (empty($code)){
            return_json(1,'请输入验证码');
        }

        //tp验证
        if(!captcha_check($code)){
            return_json(1,'验证码不正确');
        }

        //数据库查询
        $admin = Db::table('admin_users')->where('username',$username)->find();
        if(empty($admin)){
            return_json(1,'未找到该用户');
        }

        if($admin['password']!=md5($password)){
            return_json(1,'密码不正确');
        }

        if($admin['status']!=1){
            return_json(1,'用户异常,联系管理员');
        }
        //登录成功 保存Cookie
        Cookie::set('admin_id',$admin['id']);
        Db::table('admin_users')->where('id',$admin['id'])->update([
            'time_last' => time(),
            'times_login' => $admin['times_login'] + 1
        ]);
        echo json_encode(['code' => 0,'message' => '登录成功']);
        //thinkphp添加exit()还设置不了cookie
    }

    public function logout(){
        Cookie::delete('admin_id');
        return_json(0,'退出登录');
    }


}